// pkg/stats/collector.go
package stats

import (
	"sync"
	"time"
)

// Metrics 指标数据
type Metrics struct {
	Timestamp        time.Time
	SnapshotCount    int64
	TotalSize        int64
	CachedSize       int64
	DedupRatio       float64
	DownloadCount    int64
	DownloadBytes    int64
	CacheHitRate     float64
	AverageFetchTime time.Duration
}

// Collector 指标收集器
type Collector struct {
	mu      sync.RWMutex
	metrics *Metrics
	history []Metrics
	maxHist int

	// 计数器
	cacheHits   int64
	cacheMisses int64
	fetchTimes  []time.Duration
}

// NewCollector 创建收集器
func NewCollector(maxHistory int) *Collector {
	return &Collector{
		metrics:    &Metrics{Timestamp: time.Now()},
		history:    make([]Metrics, 0),
		maxHist:    maxHistory,
		fetchTimes: make([]time.Duration, 0),
	}
}

// RecordCacheHit 记录缓存命中
func (c *Collector) RecordCacheHit() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.cacheHits++
}

// RecordCacheMiss 记录缓存未命中
func (c *Collector) RecordCacheMiss() {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.cacheMisses++
}

// RecordFetchTime 记录获取时间
func (c *Collector) RecordFetchTime(d time.Duration) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.fetchTimes = append(c.fetchTimes, d)

	// 保持最近的 100 条记录
	if len(c.fetchTimes) > 100 {
		c.fetchTimes = c.fetchTimes[len(c.fetchTimes)-100:]
	}
}

// RecordDownload 记录下载
func (c *Collector) RecordDownload(bytes int64) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.metrics.DownloadCount++
	c.metrics.DownloadBytes += bytes
}

// UpdateMetrics 更新指标
func (c *Collector) UpdateMetrics(m *Metrics) {
	c.mu.Lock()
	defer c.mu.Unlock()

	m.Timestamp = time.Now()
	m.CacheHitRate = float64(c.cacheHits) / float64(c.cacheHits+c.cacheMisses)

	// 计算平均获取时间
	if len(c.fetchTimes) > 0 {
		totalTime := int64(0)
		for _, t := range c.fetchTimes {
			totalTime += int64(t)
		}
		m.AverageFetchTime = time.Duration(totalTime / int64(len(c.fetchTimes)))
	}

	c.metrics = m

	// 保存到历史
	if len(c.history) >= c.maxHist {
		c.history = c.history[1:]
	}
	c.history = append(c.history, *m)
}

// GetMetrics 获取当前指标
func (c *Collector) GetMetrics() *Metrics {
	c.mu.RLock()
	defer c.mu.RUnlock()

	// 返回副本
	m := *c.metrics
	return &m
}

// GetHistory 获取历史数据
func (c *Collector) GetHistory(limit int) []Metrics {
	c.mu.RLock()
	defer c.mu.RUnlock()

	if limit > len(c.history) {
		limit = len(c.history)
	}

	result := make([]Metrics, limit)
	copy(result, c.history[len(c.history)-limit:])
	return result
}

// ---
